package bg.unisofia.fmi.tis.service;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 *
 * A utility class, used for the bean managed persisten of the hibernate.
 *
 * @author astamenov
 */
public class HibernateUtil {

    private static final ThreadLocal<Session> session = new ThreadLocal<Session>();
    private static SessionFactory sessionFactory;

    
    public static Session getSession() {
    	return getSession("hibernate.cfg.xml");
    }
    
    /**
     * Returns a new open session.
     * @return - a enw open session.
     */
    public static Session getSession(String configFile) {
        initSessionFactory(configFile);

    	 try {
             Session s = session.get();
             // Open a new Session, if this Thread has none yet
             if (s == null) {
                 if (sessionFactory == null) {
                     throw new RuntimeException("Session factory is missing!");
                 }
                 s = sessionFactory.openSession();
                 session.set(s);
             }
             return s;
         } catch (HibernateException e) {
             throw new RuntimeException("Could not get a session", e);
         }
    }

    /**
     * Initializes the session factory, that is later used to instantiate new hibernate sessions.
     */
    public static synchronized void initSessionFactory(String configFile) {
        if (sessionFactory != null) {
            // throw new RuntimeException("Session factory already exists!");
            return;
        }

        try {
            AnnotationConfiguration cfg = new AnnotationConfiguration();
            cfg.configure(configFile);
            sessionFactory = cfg.buildSessionFactory();
        } catch (Throwable te) {
            te.printStackTrace();
            throw new ExceptionInInitializerError(te);
        }
    }

    /**
     * Checks if the session factory has been initialized.
     * @return - true iff the session factory has been propoerly initialized.
     */
    public static synchronized boolean isSessionFactoryInitialized() {
    	return sessionFactory != null;
    }
}